package com.kipling.kio.server;

import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kipling.kio.core.bean.MsgBean;
import com.kipling.kio.core.intf.Packet;
import com.kipling.kio.core.task.DecodeRunnable;


/** 
 * @author KiplingLee kiplinglee@163.com
 * @version 创建时间：2017年5月11日 下午2:33:10 
 * 
 */
public class SocketChannelHandle< P extends Packet, R> {
	
	static Logger log = LoggerFactory.getLogger(SocketChannelHandle.class);
	private ServerGroupContext<P, R> serverGroupContext = null;
	
	private BlockingQueue<MsgBean> queue = new ArrayBlockingQueue<MsgBean>(100000);
	/**
	 * 获取时间间隔
	 */
	private static final int SLEEP_TIME=10;
	public SocketChannelHandle(ServerGroupContext<P, R> _serverGroupContext){		
		if(_serverGroupContext!=null){
			serverGroupContext = _serverGroupContext;
			init();
		}
	}
	private void init(){
		Thread thread = new Thread(new HandlerThread());
		thread.start();
	}
	
	public void put(MsgBean bean){
		queue.add(bean);
	}
	
	class HandlerThread implements Runnable{
		public void run() {
			while(true){
				try {
					MsgBean bean =null;
					while((bean =  queue.poll(5,TimeUnit.SECONDS)) !=null){						
						handle(bean);
					}
				} catch (InterruptedException e) {
					try {				
						// 如果异常了数据跳过
						queue.poll(5,TimeUnit.SECONDS);
						Thread.sleep(SLEEP_TIME);
					} catch (InterruptedException e1) {
					}
				}finally{
					try {
						Thread.sleep(SLEEP_TIME);
					} catch (InterruptedException e) {
					}
				}
			
			}
		}
	}
	
	private void handle(MsgBean bean){
		ByteBuffer byteBuffer = bean.getByteBuffer(); 

        	
//        		byteBuffer.flip();
//        		String received = Charset.forName("utf-8").newDecoder().decode(byteBuffer).toString();
//    			System.out.println("DecodeRunnable.run:received:"+received);
		//byteBuffer.flip();
    	DecodeRunnable<P,R> decodeRunnable = serverGroupContext.getDecodeRunnable();
    	decodeRunnable.setBean(bean);
    	//decodeRunnable.setNewByteBuffer(byteBuffer);
    	decodeRunnable.run();
        	
	}
	public static void main(String[] args) {


	}

}
